package com.ego.dao.impl;

import com.ego.dao.RegisterDao;
import com.ego.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author 袁梦达 2019012364
 */
public class RegisterDaoImpl implements RegisterDao {

    public static final int EXISTS = -1; //已经存在
    public static final int ERROR = 0; //注册失败
    public static final int SUCCESS = 1; //注册成功


    /**
     * 判断number是否已经存在
     * @param number
     * @return false表示不可以注册 true表示可以注册
     */
    private boolean checkValid(String number){
        Connection connection = JDBCUtils.getConnection();
        PreparedStatement statement = null;
        try {
            String sql = "select * from user where number = ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1, number);
            if(statement.executeQuery().next()){
                return false;
            }
            return true;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtils.close(statement, connection);
        }
        return true;
    }

    @Override
    public Integer register(String number, String password, String name){
        if(checkValid(number)){
            //number未被注册
            Connection connection = JDBCUtils.getConnection();
            PreparedStatement statement = null;
            try {
                String sql = "insert into user values(?, ?, ?)";
                statement = connection.prepareStatement(sql);
                statement.setString(1, number);
                statement.setString(2, password);
                statement.setString(3, name);
                int rowCount = statement.executeUpdate();
                if(rowCount > 0){
                    return RegisterDaoImpl.SUCCESS;
                }
                return RegisterDaoImpl.ERROR;
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }finally {
                JDBCUtils.close(statement, connection);
            }
        }
        System.out.println("该账号已被注册");
        return RegisterDaoImpl.EXISTS;
    }
}
